
import {get_token} from '../utils/token'

/**
 * 
 * 封装HTTP请求的方法;状态码为200时，直接返回data,当非此情况时，返回fail(res)
 */
const httpPost = (url, data, success, fail) => {
  let token = get_token();
  wx.request({
    url: url,
    data: data,
    method: 'POST',
    responseType: 'text',
    header: {
      "Content-Type": "application/json",
      "token":token
    },
    dataType: 'json',
    success: function (res) {
      console.log("1111:"+JSON.stringify(res))

      if (res.data.status === 200) {
        success(res.data)
      } else {
        wx.showToast({
          title: res.data.msg,
          icon:"none"
        })
      }
    },
    fail: function (res) {
      fail(res);
    }
  });
}


const postUpload = (url, data, success, fail) => {
  let token = get_token();
  let header = {};
  if (token) {
    header.token = token
  }
  return new Promise(resolve => {
    wx.uploadFile({
      url: url,
      filePath: data,
      name: 'file',
      header: header,
      success(res) {
        let data = JSON.parse(res.data);
        if (data.status === 200) {
          resolve(data.data);
        } else {
          wx.showToast({
            title: '上传失败',
            icon: "none"
          })
        }
      },
      fail: error => {
        console.log(error)
      }
    })
  })
}




const httpGet = (url, data, success, fail) => {
  let token = get_token();
  wx.request({
    url: url,
    data: data,
    method: 'GET',
    dataType: 'json',
    header: {
      "Content-Type": "application/json",
      "token":token
    },
    responseType: 'text',
    success: function(res) {
      if (res.data.status === 200) {
        success(res.data)
      } else {
        wx.showToast({
          title: res.data.msg,
          icon:"none"
        })
      }
    },
    fail: function(res) {
      fail(res);
    }
  });
}



export const get = httpGet;
export const post = httpPost;
export const post_upload = postUpload;